<?php
/**
 * Created by PhpStorm.
 * User: fuyu
 * Date: 2018/5/29
 * Time: 下午10:14
 */

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth',['only'=>[
            'logout',
            'register',
            'info',
            'resetPassword',
            'list'
        ]]);
    }

    /**
     * 新建一个root用户，保留的member_id 10000
     */
    public function init()
    {
        $user = User::where('member_id',10000)->first();
        if ($user) {
            return response()->json(['code'=>1,'message'=>'已经初始化完成,请不要重复操作']);
        } else {
            $data = [
                'member_id' => 10000,
                'password' => Hash::make('111111'),
                'admin_name' => 'root',
                'type' => User::TYPE_SUPER
            ];
            User::create($data);
            return jsonSuccess('操作完成,默认用户root,默认密码111111');
        }
    }

    public function register(Request $request)
    {
        $user = Auth::user();
        if (!$user->can('super-user')) {
            jsonCode(403,'没有该操作权限');
        }
        $this->validate($request,[
            'member_id' => 'required|unique:admin_member,member_id|regex:/^1\d{10}$/',
            'password' => 'required|min:6',
            //'password' => 'required|min:6|confirmed',
            //'password_confirmation' => 'required|min:6',
            'admin_name' => 'required|max:10',
            'type' => ['required','regex:/1|2/']
        ]);
        $data = $request->post();
        $data['password'] = Hash::make($data['password']);
        User::create($data);
        return response()->json(['code'=>0,'message'=>'操作成功']);
    }

    public function modify(Request $request)
    {
        $user = Auth::user();
        if (!$user->can('super-user')) {
            jsonCode(403,'没有该操作权限');
        }
        $this->validate($request,[
            'id' => 'required|integer',
            'password' => 'min:6',
            'admin_name' => 'required|max:10',
            'type' => ['required','regex:/1|2/']
        ]);
        $user = User::find($request->post('id'));
        if (empty($user)) {
            return jsonFail('找不到该管理员');
        }else{
            $data = [
                'admin_name'=>$request->post('admin_name'),
                'type'=>$request->post('type'),
            ];
            if($request->post('password')!=''){
                $data['password'] = Hash::make($request->post('password'));
            }
            $user = User::where('id', $request->post('id'))
            ->update($data);
        }
        return response()->json(['code'=>0,'message'=>'操作成功']);
    }

    public function delete(Request $request)
    {
        $user = Auth::user();
        if (!$user->can('super-user')) {
            jsonCode(403,'没有该操作权限');
        }
        $this->validate($request,[
            'id' => 'required|integer',
        ]);
        $user = User::find($request->post('id'));
        if (empty($user)) {
            return jsonFail('找不到该管理员');
        }else{
            $user = User::where('id', $request->post('id'))
            ->delete();
        }
        return response()->json(['code'=>0,'message'=>'操作成功']);
    }

    public function list(Request $request)
    {
        $pageSize = $request->input('page_size',20);
        $keyword = $request->input('keyword','');
        if($keyword==''){
            $users = User::select()->orderBy('id', 'desc')->paginate($pageSize);
        }else{
            $users = User::where('member_id', 'like', '%'.$keyword.'%')
            ->orWhere('admin_name', 'like', '%'.$keyword.'%')
            ->orderBy('id', 'desc')->paginate($pageSize);
        }
        
        $pagination = ['current_page'=>$users->currentPage(),'last_page'=>$users->lastPage(),'total'=>$users->total()];
        return jsonSuccess('获取成功',['list'=>$users->items(),'pagination'=>$pagination]);
    }

    public function get(Request $request)
    {
        $this->validate($request,[
            'id' => 'required'
        ]);
        $user = User::find($request->get('id'));
        if (empty($user)) {
            return jsonFail('找不到该用户');
        }
        return jsonSuccess('获取成功',$user);
    }

    public function login(Request $request)
    {
        $this->validate($request,[
            'member_id' => ['required','regex:/^(1\d{10})|10000$/'],
            'password' => 'required|min:6'
        ]);
        $user = User::where(['member_id'=>$request->post('member_id')])->first();
        if (!$user) {
            return response()->json(['code'=>1,'message'=>'用户名或密码错误']);
        } else {
            if (!Hash::check($request->post('password'),$user->password)) {
                return response()->json(['code'=>1,'message'=>'用户名或密码错误']);
            }
            $token = str_random(60);
            $user->api_token = $token;
            $user->save();
            return jsonSuccess('登陆成功',['token'=>$user->api_token]);
        }
    }

    public function logout(Request $request)
    {
        $user = Auth::user();
        $user->api_token = '';
        $user->save();
        return jsonSuccess('注销成功');
    }

    public function info(Request $request)
    {
        $user = Auth::user();
        return jsonSuccess('获取成功',['user_info'=>$user]);
    }

    public function resetPassword (Request $request)
    {
        $this->validate($request,[
            'password' => 'required|min:6',
            'new_password' => 'required|min:6',
            'password_confirmation' => 'required|min:6'
        ]);
        if ($request->post('new_password')===$request->post('password')) {
            return response()->json(['code'=>1,'message'=>'新密码与原密码一致']);
        }
        if ($request->post('new_password')!=$request->post('password_confirmation')) {
            return response()->json(['code'=>1,'message'=>'确认密码错误']);
        }
        $user = Auth::user();
        if (!Hash::check($request->post('password'),$user->password)) {
            return response()->json(['code'=>1,'message'=>'原密码错误']);
        }
        $user->password = Hash::make($request->post('new_password'));
        $user->save();
        return jsonSuccess('密码修改成功');
    }

}